"""
主路由模块
处理首页、邮件列表、发送邮件等主要功能页面
"""
from flask import render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user
from app.main import bp
from app.models import User, Email
from app import db

@bp.route('/')
def index():
    """
    首页路由
    未登录用户显示登录页面，已登录用户跳转到收件箱
    """
    if current_user.is_authenticated:
        return redirect(url_for('main.inbox'))
    return redirect(url_for('auth.login'))

@bp.route('/inbox')
@login_required
def inbox():
    """
    收件箱页面
    显示当前用户的收件箱邮件列表
    """
    page = request.args.get('page', 1, type=int)
    per_page = 10
    
    # 获取收件箱邮件（未被接收者删除）
    emails = Email.query.filter_by(
        recipient_id=current_user.id,
        is_deleted_by_recipient=False
    ).order_by(Email.sent_at.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    return render_template('inbox.html', 
                         title='收件箱', 
                         emails=emails,
                         unread_count=current_user.get_unread_count())

@bp.route('/sent')
@login_required
def sent():
    """
    发件箱页面
    显示当前用户发送的邮件列表
    """
    page = request.args.get('page', 1, type=int)
    per_page = 10
    
    # 获取发件箱邮件（未被发送者删除）
    emails = Email.query.filter_by(
        sender_id=current_user.id,
        is_deleted_by_sender=False
    ).order_by(Email.sent_at.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    return render_template('sent.html', 
                         title='发件箱', 
                         emails=emails)

@bp.route('/compose')
@login_required
def compose():
    """
    写邮件页面
    显示邮件编写表单
    """
    # 获取所有用户列表（除了当前用户）
    users = User.query.filter(User.id != current_user.id, User.is_active == True).all()
    return render_template('compose.html', title='写邮件', users=users)

@bp.route('/email/<int:email_id>')
@login_required
def view_email(email_id):
    """
    查看邮件详情
    
    Args:
        email_id: 邮件ID
    """
    email = Email.query.get_or_404(email_id)
    
    # 检查权限：只有发送者或接收者可以查看
    if email.sender_id != current_user.id and email.recipient_id != current_user.id:
        flash('您没有权限查看此邮件。', 'error')
        return redirect(url_for('main.inbox'))
    
    # 检查邮件是否被当前用户删除
    if (email.recipient_id == current_user.id and email.is_deleted_by_recipient) or \
       (email.sender_id == current_user.id and email.is_deleted_by_sender):
        flash('邮件不存在或已被删除。', 'error')
        return redirect(url_for('main.inbox'))
    
    # 如果是接收者查看邮件，标记为已读
    if email.recipient_id == current_user.id and not email.is_read:
        email.mark_as_read()
    
    return render_template('view_email.html', title='邮件详情', email=email)

@bp.route('/send_email', methods=['POST'])
@login_required
def send_email():
    """
    发送邮件API
    处理邮件发送请求
    """
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data or not all(k in data for k in ('recipient', 'subject', 'content')):
            return jsonify({'success': False, 'message': '请填写完整的邮件信息'}), 400
        
        recipient_username = data['recipient'].strip()
        subject = data['subject'].strip()
        content = data['content'].strip()
        
        # 验证字段不为空
        if not recipient_username or not subject or not content:
            return jsonify({'success': False, 'message': '邮件信息不能为空'}), 400
        
        # 查找接收者
        recipient = User.query.filter_by(username=recipient_username, is_active=True).first()
        if not recipient:
            return jsonify({'success': False, 'message': f'用户 "{recipient_username}" 不存在'}), 404
        
        # 不能给自己发邮件
        if recipient.id == current_user.id:
            return jsonify({'success': False, 'message': '不能给自己发送邮件'}), 400
        
        # 创建邮件
        email = Email(
            sender_id=current_user.id,
            recipient_id=recipient.id,
            subject=subject,
            content=content
        )
        
        db.session.add(email)
        db.session.commit()
        
        return jsonify({
            'success': True, 
            'message': f'邮件已成功发送给 {recipient.username}',
            'email_id': email.id
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'发送失败：{str(e)}'}), 500

@bp.route('/delete_email/<int:email_id>', methods=['POST'])
@login_required
def delete_email(email_id):
    """
    删除邮件API
    
    Args:
        email_id: 邮件ID
    """
    try:
        email = Email.query.get_or_404(email_id)
        
        # 检查权限
        if email.sender_id != current_user.id and email.recipient_id != current_user.id:
            return jsonify({'success': False, 'message': '您没有权限删除此邮件'}), 403
        
        # 根据用户角色删除邮件
        if email.sender_id == current_user.id:
            email.delete_by_sender()
        elif email.recipient_id == current_user.id:
            email.delete_by_recipient()
        
        # 如果双方都删除了，从数据库中物理删除
        if email.is_deleted():
            db.session.delete(email)
            db.session.commit()
        
        return jsonify({'success': True, 'message': '邮件已删除'})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'删除失败：{str(e)}'}), 500

@bp.route('/mark_read/<int:email_id>', methods=['POST'])
@login_required
def mark_read(email_id):
    """
    标记邮件为已读
    
    Args:
        email_id: 邮件ID
    """
    try:
        email = Email.query.get_or_404(email_id)
        
        # 只有接收者可以标记为已读
        if email.recipient_id != current_user.id:
            return jsonify({'success': False, 'message': '您没有权限操作此邮件'}), 403
        
        email.mark_as_read()
        
        return jsonify({'success': True, 'message': '邮件已标记为已读'})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'操作失败：{str(e)}'}), 500

@bp.route('/search')
@login_required
def search():
    """
    邮件搜索功能
    """
    query = request.args.get('q', '').strip()
    page = request.args.get('page', 1, type=int)
    per_page = 10
    
    if not query:
        flash('请输入搜索关键词', 'warning')
        return redirect(url_for('main.inbox'))
    
    # 搜索邮件（主题或内容包含关键词）
    emails = Email.query.filter(
        db.or_(
            db.and_(
                Email.recipient_id == current_user.id,
                Email.is_deleted_by_recipient == False,
                db.or_(
                    Email.subject.contains(query),
                    Email.content.contains(query)
                )
            ),
            db.and_(
                Email.sender_id == current_user.id,
                Email.is_deleted_by_sender == False,
                db.or_(
                    Email.subject.contains(query),
                    Email.content.contains(query)
                )
            )
        )
    ).order_by(Email.sent_at.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    return render_template('search_results.html', 
                         title=f'搜索结果: {query}', 
                         emails=emails, 
                         query=query)